Repository navigation
feat: Optimize the loading style of the conversation - #8293
Conversation
|
|
||
| // 通用发送能力,由消息列表或外部宿主(如工具调试结果抽屉)提供;内容项按自身场景组装参数。 | ||
| export type SendMessage = (opts: SendMessageOptions) => void | ||
|
|
There was a problem hiding this comment.
Here's my review of the code changes:
Summary
The changes add a streamingMessage ref to track which message is currently being streamed, plus an injection key/helper so content items can know if their parent answer is actively streaming (to avoid a stale "running" indicator after completion).
Potential Issues
1. Race condition risk with currentStream = null in multiple places
In runStream, closeStream() is called first (which resets state and sets streamingMessage.value = null), then immediately streamLoading.value = true and streamingMessage.value = target. This looks fine sequentially, but if request() is slow and another runStream is invoked before the promise resolves, the earlier .then handler will overwrite currentStream — there's no guard that the resolved response still belongs to the current call. Consider capturing a token/id:
const token = ++streamToken
request().then((response) => {
if (token !== streamToken) { /* abort or ignore */ }
...
})This existed before your change but adding target makes it more consequential — streamingMessage.value = null in a stale .catch/onComplete could wrongly clear an active new stream.
2. streamingMessage set before response resolves
streamingMessage.value = target is set synchronously when runStream begins, before the request resolves. If request() throws or fails, streamingMessage is correctly reset in .catch, but content items will briefly render "running" during the request handshake. Likely acceptable, just confirm this matches the desired UX.
3. computed(() => streamingMessage.value) wrapper is redundant
streamingMessage: computed(() => streamingMessage.value),Since streamingMessage is already a Readonly-ish shallowRef, wrapping it in a computed adds overhead without benefit. Consumers needing read-only can type it as Readonly<Ref<...>>. If you want to expose it immutably, prefer exposing the ref directly and relying on types, or use readonly where appropriate. Minor.
4. useMessageStreaming returns a static false ref when not provided
return inject(MESSAGE_STREAMING_KEY, ref(false))The default ref(false) is created fresh per call — fine functionally, but allocating a new ref each call is slightly wasteful. A module-level constant const NEVER_STREAMING = ref(false) (or readonly(ref(false))) can be shared. Verify the consumer only needs truthiness and won't mutate it.
5. TypeScript typing of the provided value
MESSAGE_STREAMING_KEY expects Readonly<Ref<boolean>>, but the store exports streamingMessage: computed(...) typed as ComputedRef<ChatMessage | null>. There seems to be no wiring shown here — ensure that wherever MESSAGE_STREAMING_KEY is provided, it's derived properly:
provide(MESSAGE_STREAMING_KEY, computed(() => store.streamingMessage.value?.id === props.message.id))Otherwise the name mismatch (streamingMessage is ChatMessage | null, while the key is boolean) may lead to confusion. Worth confirming the provider code exists and correct.
6. Cleanup guarantee on unmount
streamingMessage.value is reset in closeStream, onComplete, and .catch. Ensure the store also calls closeStream() on component unmount/dispose so streamingMessage doesn't remain dangling. Not shown in the diff — verify.
7. Comment says "与 streamLoading 同步复位" (reset in sync with streamLoading)
Double-check every place streamLoading.value = false occurs — the three shown spots are updated, but grep for others (e.g., abort paths, error boundaries). Any missed spot leaves streamingMessage stale.
Optimization Suggestions
- Extract a helper like
resetStreamState()to setcurrentStream = null; streamLoading.value = false; streamingMessage.value = nullatomically in one place, reducing duplication across the aborted/failed/succeeded branches. - Consider deriving
streamLoadingfromstreamingMessage.value != nullif they truly always move together — eliminates the duplicate-state bug class entirely. - Guard against stale promises with a sequence counter (point 1) — most impactful robustness fix.
Verdict
The intent and structure are sound, comments are helpful. The main real concern is the stale-promise race (issue #1), which pre-existed but is now amplified since streamingMessage will be cleared by an outdated completion. Fix that and extract the reset helper; the rest are minor cleanups.
| <span class="-mx-1" :class="{ 'mk-dotting': content.status === 'RUNNING' && streaming }"> | ||
| {{ content.status === 'RUNNING' ? t('chat.message.thinking') : t('chat.message.thinkingCompleted') }} | ||
| </span> | ||
| </template> |
There was a problem hiding this comment.
Review of the diff
🔴 Potential bugs
-
Boolean coercion of
streamingin the template is unsafe.
Old code readmessageList?.streamLoading.value, which yields a real boolean.
New code usesstreamingdirectly. This only works ifuseMessageStreaming()returns aRef<boolean>/ComputedRef<boolean>(auto-unwrapped in the template).- If it returns a composable object (e.g.
{ isStreaming, ... }) or a function,streamingis always truthy →mk-dottinganimates unconditionally. This is the most likely regression. - Verify the return type, and if it isn't a pure boolean ref, use
streaming.isStreaming/streaming()and consider!!orBoolean().
- If it returns a composable object (e.g.
-
Lost "optional context" tolerance.
inject(MESSAGE_LIST_KEY, null)had anulldefault andmessageList?.optional chaining, so the component worked outside a message list (unit tests, Storybook, standalone/SSR usage). IfuseMessageStreaming()callsinjectwithout a default (or throws when no provider exists), this now breaks in those contexts. Check the composable's injection behavior. -
Semantics may have changed.
Previously the animation depended on that message list instance'sstreamLoading. IfuseMessageStreaming()exposes a global/app-level streaming flag, then everyRUNNINGreasoning block across all messages would animate simultaneously. Confirm the composable's scope matches the old per-list scope. -
Circular-import risk.
The component now imports from../../message-list(likely a barrel file). If that barrel re-exports components that import this component, you can get a circular dependency or an undefined import at module-eval time. Prefer importing the composable from its concrete module (e.g.../../message-list/use-message-streaming).
🟡 Redundancy / logic
-
content.status === 'RUNNING'andstreaminglikely overlap.
Ifstreamingis true only while a message is running, the status check is redundant; if they can disagree (stale status vs. stream state, or a different message running), you get wrong UI. Consider one source of truth. -
Repeated template expression.
content.status === 'RUNNING'appears twice (class binding + label text). Compute once in<script setup>:const isRunning = computed(() => props.content.status === 'RUNNING') const isThinkingStreaming = computed(() => isRunning.value && isStreaming.value)
This also makes the boolean coercion explicit and testable.
-
Naming.
streamingreads like an action/store;isStreamingcommunicates a boolean. Helps prevent the bug in point 1.
🟢 Minor / style
-
definePropsresult not assigned. Fine in template, but if you compute the derived flags above you'll needconst props = defineProps<...>(). Also consider extracting the inline prop type ({ content?: string | null; status?: string }) into a named interface for reuse and to makestatusa string-literal union instead ofstring. -
useTemplateRef<HTMLElement>('reasoningScrollRef')passed inline touseBottomFollow. Works, but storing it in aconstimproves readability and lets you reuse it (e.g., for awatch/nextTickscroll-to-bottom when expanding). Note it'sHTMLElementwhile the ref presumably targets a scroll container —HTMLElementis fine,HTMLDivElementis tighter. -
No watcher on
isExpanded/ new content. If the panel can be expanded while content streams, verifyuseBottomFollowstill responds to height changes (dependency array / ResizeObserver). Not caused by this diff, but worth confirming since the streaming source changed.
Suggested shape
const props = defineProps<{
content: { content?: string | null; status?: 'RUNNING' | 'COMPLETED' | string }
}>()
const { isStreaming } = useMessageStreaming() // confirm actual API
const isRunning = computed(() => props.content.status === 'RUNNING')
const showDotting = computed(() => isRunning.value && Boolean(unref(isStreaming)))<span class="-mx-1" :class="{ 'mk-dotting': showDotting }">Bottom line: the refactor is fine if useMessageStreaming() returns a boolean ref, tolerates a missing provider, and is list-scoped rather than global. Verify those three things; otherwise the dotting indicator can become always-on or the component can fail outside a message-list context.
| :loading="streaming && toolItem.status === 'RUNNING'" | ||
| :expanded="isToolExpanded(toolItem, index)" | ||
| @update:expanded="manualToolExpanded[toolKey(toolItem, index)] = $event" | ||
| @toggle="toggleTool(toolItem, index)" |
There was a problem hiding this comment.
The patch is syntactically fine for Vue 3, but there are a few semantic and maintainability points to verify.
Potential issues
-
Scope of
useMessageStreaming()- Verify that
useMessageStreaming()returns the streaming state for this specific message/answer, not a global “any message is streaming” flag. - If it is global, a completed tool group could still show running while another answer streams, or a valid running tool could be suppressed if the state is not yet updated.
- The comment says “所属回答结束后” (after the owning answer ends), so the composable should be message-scoped.
- Verify that
-
Stale
RUNNINGstatus becomessuccessif (streaming.value && childStatuses.includes('RUNNING')) return 'running' ... return childStatuses.length ? 'success' : ''
When streaming ends but a tool status is still
RUNNING,groupStatusfalls through to'success'. That avoids the spinner, but it may incorrectly display a successful group for an aborted/failed/incomplete stream.- Consider explicitly handling stale
RUNNING:- Normalize tool statuses when streaming ends, or
- Show an “unknown/incomplete” state instead of unconditional
'success'.
- Consider explicitly handling stale
-
Import path / circular dependency risk
import { useMessageStreaming } from '../../../message-list'
- Importing from a barrel/index module like
message-listcan create a circular dependency if that module indirectly imports this component. - Prefer importing directly from the composable file, and/or use the project alias, e.g.
@/.../useMessageStreaming.
- Importing from a barrel/index module like
-
Boolean prop type
:loading="streaming && toolItem.status === 'RUNNING'"
In templates, top-level refs are auto-unwrapped, so this is correct if
streamingis a top-levelRef<boolean>. Do not change it tostreaming.valuein the template.- If
streamingcan beundefined, consider forcing a boolean:or use a helper.:loading="!!(streaming && toolItem.status === 'RUNNING')"
- If
Optimization suggestion
Extract the repeated condition into a single helper to keep groupStatus and the template consistent:
const isToolRunning = (toolItem: ChatContent) =>
streaming.value && toolItem.status === 'RUNNING'Then:
const groupStatus = computed(() => {
const childStatuses = toolItems.value.map((toolItem) => toolItem.status)
if (toolItems.value.some(isToolRunning)) return 'running'
if (childStatuses.some((s) => s === 'FAIL' || s === 'FAILURE')) return 'error'
return childStatuses.length ? 'success' : ''
}):loading="isToolRunning(toolItem)"Minor notes
- The
.valueusage insidecomputedis correct. - The template usage without
.valueis correct due to Vue ref auto-unwrapping. - Consider adding tests for:
streaming = true+ toolRUNNING→ spinner shown.streaming = false+ toolRUNNING→ no spinner.streaming = false+ toolFAIL→ error state.- Empty tool list → empty group status.
Main risk: using a possibly global streaming state and mapping stale RUNNING to success.
feat: Optimize the loading style of the conversation